<script>
import { api } from '@/api';
import dayjs from 'dayjs';
import { Grid, GridItem, Image, ImagePreview, List } from 'vant';

export default {
  components: {
    Grid,
    GridItem,
    [Image.name]: Image,
    List
},
  computed: {
    images() {
      return this.list.map(item => item.file_url).filter(Boolean)
    }
  },
  data() {
    return {
      list: [],
      page: 0,
      loading: false,
      finished: false
    }
  },
  methods: {
    async getList() {
      const { data, count } = await api.space.list(this.page++)

      if (!Array.isArray(data) || !data.length) return true

      this.list.push(...data.map(item => ({
        ...item,
        file_url: item.file_url ? item.file_url : '',
        create_time: dayjs(item.create_time).format('M月D日 HH:mm')
      })))

      return this.list.length >= count
    },
    previewImages(url) {
      ImagePreview({
        images: [url],
        startPosition: 0
      })
    },
    async handleLoad() {
      this.finished = await this.getList()
      this.loading = false
    }
  },
}
</script>

<template>
  <div class="space-view">
    <List v-model="loading" :finished="finished" finished-text="没有更多了" @load="handleLoad">
      <div class="space-list">
        <div v-for="item in list" :key="item.article_id" class="space-item">
          <img class="space-item-avatar" :src="item.avatar_url ? item.avatar_url : undefined" alt="">

          <div class="space-item-info">
            <div class="space-item-content">{{ item.article_title }}</div>
            <div v-html="item.article_content"></div>
            <div class="space-item-images">
              <van-image v-if="item.file_url" fit="cover"  radius="3" :src="item.file_url ? item.file_url : undefined" @click="previewImages(item.file_url)" />
            </div>

            <div class="space-item-date">
              {{ item.create_time }}
            </div>
          </div>
        </div>
      </div>
    </List>
  </div>
</template>

<style lang="less" scoped>
.space-view {
  height: 100%;

  /deep/ .van-image>img {
    aspect-ratio: 1 / 1;
  }

  .space-item {
    padding: 15px;
    display: flex;
    gap: 10px;

    &-avatar {
      width: 50px;
      height: 50px;
      border-radius: 4px;
      object-fit: cover;
      flex-shrink: 0;
    }

    &-info {
      display: flex;
      flex-direction: column;
      gap: 10px;
    }

    &-content {
      // 2行缩略
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
      padding-top: 2px;
    }

    &-images {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 5px;
    }

    &-date {
      font-size: 12px;
      color: #999;
    }

    &:not(:last-child) {
      border-bottom: 1px solid #f0f0f0;
    }
  }
}
</style>
